﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using WSS.Models.User;
using WSS.Pub;


namespace WSS.BLL.User
{
    public class UserImport
    {
        /// <summary>
        /// 导入文件的物理路径
        /// </summary>
        private string _FILE_PHYSICAL_PATH { get; set; }

        private string _HOSP_ID { get; set; }

        private int _LATEST_USEID { get; set; }

        List<DBState> _LIST_DBSTATE = new List<DBState>();

        /// <summary>
        /// 导入文件转成的 DataTabel
        /// </summary>
        private DataTable _XLS_CONCTENT { get; set; }

        public UserImport(string filename, string hosptialid)
        {
            var import_path = Utils.AppConfigHelper.GetValue("Uploadify_SaveTo");
            import_path += "/" + filename;
            _FILE_PHYSICAL_PATH = System.Web.HttpContext.Current.Server.MapPath(import_path);

            if (!System.IO.File.Exists(_FILE_PHYSICAL_PATH))
            {
                throw new Exception("文件在不存在");
            }

            System.IO.FileInfo fi = new System.IO.FileInfo(_FILE_PHYSICAL_PATH);
            if (fi.Extension.ToUpper() == ".XLSX")
            {
                _XLS_CONCTENT = Utils.XlsxHelper.XlsxToDataTabel(_FILE_PHYSICAL_PATH);
            }
            else
            {
                _XLS_CONCTENT = Utils.XlsHelper.XlsToDataTabel(_FILE_PHYSICAL_PATH);
            }
            
            _HOSP_ID = hosptialid;

            _CheckColHead();
            _CheckContent();
            _Import();
        }


        private string get_blue_html(string val)
        {
            return "<span style='color:blue;'>" + val + "</span>";
        }
        private int get_gender(object val)
        {
            var strval = Pub.Utils.GetString(val);

            if (strval == "")
            {
                return 1;
            }

            if (strval.Trim() == "男" || strval == "01")
            {
                return 1;
            }
            if (strval.Trim() == "女" || strval == "02")
            {
                return 2;
            }

            return 0;
        }

        /// <summary>
        /// 数据库中某医院的用户工号集合，用于判断导入数据中的用户工号是否在库中存在
        /// </summary>
        /// <param name="hosp_id"></param>
        /// <returns></returns>
        private List<string> get_db_userno(string hosp_id)
        {
            var list = new List<string>();
            var s = "SELECT user_no FROM USER_USER WHERE HOSP_ID = '" + hosp_id + "'";
            var o = DB.Select(s);

            if (o.Count > 0)
            {
                foreach (StrObjDict sod in o)
                {
                    list.Add(Pub.Utils.GetString(sod, "USER_NO"));
                }
            }
            return list;
        }

        private void _CheckColHead()
        {
            string[] arr_header = new string[] { "工号", "姓名", "性别", "手机", "QQ", "邮箱" };

            string errors = "";

            DataColumnCollection row = _XLS_CONCTENT.Columns;
            foreach (DataColumn column in row)
            {
                if (!arr_header.Contains(column.ColumnName))
                {
                    errors += column.ColumnName + ";";
                }
            }

            if (errors != "")
            {
                throw new Exception("发现不能识别的导入列：" + errors);
            }
        }

        private void _CheckContent()
        {
            if (_XLS_CONCTENT.Rows.Count == 0)
            {
                throw new Exception("您上传的是空白文件");
            }

            List<string> listerror = new List<string>();
            List<string> gonghao = new List<string>();
            List<string> gonghao_db = get_db_userno(_HOSP_ID);

            string userid = BLL.Xt.XhbManager.Instance.GetXh("USER_USER");
            int uid = int.Parse(userid);

            for (int i = 0; i < _XLS_CONCTENT.Rows.Count; i++)
            {

                DataRow dr = _XLS_CONCTENT.Rows[i];

                bool haswrong = false;
                string err = "第" + get_blue_html((i + 1).ToString()) + "行: ";

                USER_USER user = new USER_USER();

                user.FLAG_LOGIN = 1;
                user.FLAG_MAIL = 0;
                user.FLAG_PHONE = 0;
                user.HOSP_ID = _HOSP_ID;
                user.USER_EMAIL = Pub.Utils.GetString(dr["邮箱"]);

                user.USER_GENDER = get_gender(dr["性别"]);
                if (user.USER_GENDER == 0)
                {
                    haswrong = true;
                    err += "用户性别应当为男或女;";
                }

                user.USER_IDCARD = "";
                user.USER_NAME = Pub.Utils.GetString(dr["姓名"]);
                user.USER_NO = Pub.Utils.GetString(dr["工号"]);
                if (user.USER_NAME.IsNullOrEmpty())
                {
                    haswrong = true;
                    err += get_blue_html("姓名") + "不可以为空;";
                }
                if (user.USER_NO.IsNullOrEmpty())
                {
                    haswrong = true;
                    err += get_blue_html("工号") + "不可以为空;";
                }
                else
                {
                    if (gonghao_db.Contains(user.USER_NO))
                    {
                        haswrong = true;
                        err += "工号(" + get_blue_html(user.USER_NO) + ")在系统中已存在;";
                    }
                    if (gonghao.Contains(user.USER_NO))
                    {
                        haswrong = true;
                        err += "工号(" + get_blue_html(user.USER_NO) + ")在导入文件中存在重复;";
                    }
                    else
                    {
                        gonghao.Add(user.USER_NO);
                    }
                }

                user.USER_PHONE = Pub.Utils.GetString(dr["手机"]);
                user.USER_PIC = "default.jpg";
                user.USER_PWD = Utils.MD5.MD5Encrypt("123456", 32);
                user.USER_QQ = Pub.Utils.GetString(dr["QQ"]);
                user.USER_ID = (uid + i).ToString();

                if (!haswrong)
                {
                    _LIST_DBSTATE.Add(new DBState
                    {
                        Name = user.MAP_INSERT,
                        Param = user,
                        Type = ESqlType.INSERT
                    });
                }
                else
                {
                    listerror.Add(err);
                }
            }

            string msg = "";
            foreach (string err in listerror)
            {
                msg += "<li class='list-group-item'>" + err + "</li>";
            }
            if (msg != "")
            {
                throw new Exception(msg);
            }

            _LATEST_USEID = uid + _XLS_CONCTENT.Rows.Count - 1;
        }

        private void _Import()
        {
            BLL.Xt.XhbManager.Instance.SetXh("USER_USER", _LATEST_USEID);
            DB.Execute(_LIST_DBSTATE);
        }
    }
}